package com.tz.fruit.controller;

import com.fasterxml.jackson.databind.annotation.JsonAppend;
import com.tz.fruit.entity.*;
import com.tz.fruit.service.ICartService;
import com.tz.fruit.service.IProductService;
import com.tz.fruit.service.IShoppingCart;
import com.tz.fruit.service.IUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.List;


/**
 * Created by Tyranty on 2017/7/20 0020.
 */
@Controller
@RequestMapping("/cart")
public class CartController {

    @Autowired
    private IShoppingCart iShoppingCart;
    @Autowired
    private ICartService cartService;
    @Autowired
    private IProductService productService;


    @RequestMapping("/view")
    public String cart(HttpServletRequest request, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Cart cart = cartService.findCartByUserId(user.getUserId());
        if (cart!=null) {
            List<OrderItem> orderItems = cartService.findAll(cart.getCartId());
//        iShoppingCart.clear();
            if (orderItems != null) {
                for (OrderItem o : orderItems) {
                    iShoppingCart.saveCart(o);
                }
            }
        }
        request.getSession().setAttribute("iShoppingCart", iShoppingCart);
        return "cart";
    }

    @RequestMapping("/addtocart")
    public String save(HttpSession session,HttpServletRequest request, Long pid, @RequestParam(defaultValue = "1") int num) {
        User user = (User) session.getAttribute("user");
        Long userId = user.getUserId();
        Product product = cartService.findProductByPid(pid);
        Cart cart = cartService.findCartByUserId(userId);
        OrderItem orderItem = cartService.findOrderItemByPNo(product.getpNo());
        if (cart== null) {
            cart = new Cart(0, 0, user);
            Order order = new Order(String.valueOf(user.getUserId()), new Date(), new Date(), 0.0, OrderStatus.未付款, null, null, null, null, 0, user);
            cartService.saveOrder(order);
            cartService.saveCart(cart);
        } else {
            if (orderItem == null) {
                Order order =cartService.findOrderByOrderNo(String.valueOf(user.getUserId()));
                orderItem = new OrderItem(product.getpNo(), product.getImgUrl(), product.getpName(), product.getStandard(), product.getPrice(), num, product.getPrice() * num, 0, order);
                cart.setTotal(orderItem.getTotal());
                cart.setCount(orderItem.getCount());
                orderItem.setCart(cart);
                cartService.saveOrderItem(orderItem);
                iShoppingCart.saveCart(orderItem);
                iShoppingCart.modifyCount(productService.findByPNo(orderItem.getpNo()).getPid(), num);
            } else {
                orderItem.setCount(orderItem.getCount() + num);
                iShoppingCart.modifyCount(productService.findByPNo(orderItem.getpNo()).getPid(), orderItem.getCount());
                cart.setCount(iShoppingCart.getCount());
                cartService.updateCart(cart);
                cartService.updateOrderItem(orderItem);
            }
        }
        return "redirect:view";
    }

    @RequestMapping("/modify")
    public void modify(HttpSession session,HttpServletResponse response, HttpServletRequest request) throws IOException {
        User user = (User) session.getAttribute("user");
        PrintWriter out = response.getWriter();

        iShoppingCart = (IShoppingCart) request.getSession().getAttribute("iShoppingCart");
        String itemId = request.getParameter("itemId");
        String count = request.getParameter("count");
        OrderItem orderItem = cartService.findOrderItemByItemId(Long.valueOf(itemId));
        orderItem.setCount(Integer.valueOf(count));
        cartService.updateOrderItem(orderItem);
        if (count != null) {
            iShoppingCart.modifyCount(productService.findByPNo(orderItem.getpNo()).getPid(), Integer.valueOf(count));
            out.print(iShoppingCart.getCount() + ":" + iShoppingCart.getTotal());
        }
        Long userId = user.getUserId();
        Cart cart = cartService.findCartByUserId(userId);
        cart.setCount(iShoppingCart.getCount());
        cart.setTotal(iShoppingCart.getTotal());
        cartService.updateCart(cart);
    }

    @RequestMapping("/delete")
    public String delete(HttpServletRequest request) {
        String itemId = request.getParameter("itemId");
        cartService.deleteByOrderItemId(Long.valueOf(itemId));
        iShoppingCart.delete(Long.valueOf(itemId));
        return "forward:view";
    }
}
